/*
 * @Author: 代勇 1031850847@qq.com
 * @Date: 2023-10-28 13:37:06
 * @LastEditors: daiyong 1031850847@qq.com
 * @LastEditTime: 2024-10-29 14:21:11
 * @Description:通用js
 */

//针对当前项目
export const sys = {
    /**
     * @description: 权限
     * @param {*} str 对应后台的权限字段
     * @return {*}
     */
    power: function (str) {
        if (str) {
            const strs = str.split('/').filter(item => item)
            if (strs.length == 1) str = strs[0] + '/index'
            else if (strs.length == 2) str = strs[0] + '/' + strs[1]
            else return false
            try {
                const userInfo = func.jsonStorage(config.storage.loginInfo)
                if (userInfo.id == config.allPowerId) return true
                if (userInfo.group.power.includes(str)) return true
                else return false
            } catch (error) {
                return false
            }
        }
        return true
    },
    /**
     * @description: 下载
     * @param {*} url 链接
     * @param {*} data 参数 {params:url参数,name:保存的文件名称}
     * @return {*}
     */
    download: function (url, data) {
        const loading = ElLoading.service({ text: '文件生成中请稍后...' })
        axios.get(url, {
            params: data.params || {},
            responseType: 'blob'
        }).then(response => {
            if (response instanceof Blob) {
                let saveName = data.name
                let ext = ''
                if (response.disposition) {//设置为服务器给出的格式
                    const matchServerName = response.disposition.match(/\.([\w]+)"$/);
                    if (matchServerName) ext = matchServerName[1]
                }
                if (ext != '') {
                    const matchSaveName = data.name.match(/^(.*?)\.([\w]+)$/)
                    if (matchSaveName && matchSaveName[2] != ext) {
                        saveName = matchSaveName[1] + '.' + ext
                    }
                }
                setTimeout(() => {
                    loading.close()
                    //开始下载
                    const url = URL.createObjectURL(response);
                    const link = document.createElement("a");
                    link.href = url;
                    link.download = saveName;
                    link.click();
                    URL.revokeObjectURL(url);
                }, 500)
            } else {
                loading.close()
                sys.tip(response)
            }
        }).catch(error => {
            setTimeout(() => { loading.close() }, 500)
        })
    },
    /**
    * @description: 后台返回的操作提示
    * @param {*} data 数据格式:{status:1,message:'xxx',data:[]}
    * @return {*}
    */
    tip: function (data, func) {
        let duration = data.message.length * 100
        if (duration < 3000) duration = 3000
        if (!data.hasOwnProperty('status')) {
            if (!data.hasOwnProperty('duration')) data.duration = duration
            if (!data.hasOwnProperty('grouping')) data.grouping = true
            ElMessage(data);
            return true
        }
        if (data.status != 3 && typeof func === 'function') {
            func();  // 服务器可能返回多种状态,当不是[有成功有失败]并且有func时执行
        }
        let type = 'info'
        if (data.status == 0 || data.status == 99) type = 'error' //失败或未登录
        else if (data.status == 1) type = 'success' //成功
        else if (data.status == 2 || data.status == 98) type = 'warning' //警告或无权限
        else if (data.status == 3) {//有成功有失败
            type = false
            const info = [];
            for (const i in data.message) {
                const item = data.message[i]
                let color = 'var(--el-color-color)'
                if (item.status == 1) color = 'var(--el-color-success)'
                if (item.status == 0) color = 'var(--el-color-danger)'
                info.push('<el-text style="color:' + color + '">' + item.message + '</el-text>')
            }
            ElMessageBox.alert(
                info.join('<br/>'),
                '操作提示',
                {
                    dangerouslyUseHTMLString: true,
                    draggable: true,
                    callback: () => {
                        if (typeof func === 'function') {
                            func();  // 执行函数
                        }
                    },
                }
            )
        }
        if (type !== false) {
            ElMessage({
                message: data.message,
                type: type,
                grouping: true,
                duration: duration,
                showClose: duration >= 5000 ? true : false
            });
        }
    }
}
//验证字符串格式`
export const verify = {
    isMail: function isMail($value) { //是否是邮箱
        return /^[\w]+@[\w]+(\.[\w]+){1,}$/.test($value);
    },
    isPhone: function isPhone($value) { //是否是手机
        return /^1[\d]{10}$/.test($value);
    },
    isDate: function isDate($value) { //2024-01-23,2024/1/31
        return /^[\d]{4}(\-|\/)([0-1]|)[\d](\-|\/)([0-3]|)[\d]$/.test($value);
    },
    isTime: function isTime($value) { //2024-01-23 01:23:34,2024/1/31 1:3:4
        return /^[\d]{4}(\-|\/)([0-1]|)[\d](\-|\/)([0-3]|)[\d] ([0-2]|)[\d]:([0-5]|)[\d]:([0-5]|)[\d]$/.test($value);
    }
}
//js通用方法
export const func = {
    /**
     * @description: 删除一维数组或对象中的空值
     * @param {*} object 一维数组或对象
     * @param {*} stringArr 默认['', null, undefined]
     * @return {*}
     */
    clearData: function (object, stringArr = ['', null, undefined]) {
        const data = Array.isArray(object) ? [] : {};
        for (const i in object) {
            const item = object[i];
            if (stringArr.indexOf(item) == -1) {
                if (Array.isArray(data)) {
                    data.push(item);
                } else {
                    data[i] = item;
                }
            }
        }
        return data;
    },
    /**
     * @description: 设置或获取json storage
     * @param {*} key storage的key值
     * @param {*} data 如果不为空则返回json storage
     * @return {*}
     */
    jsonStorage: function (key, data) {
        let storage = {}
        try {
            storage = JSON.parse(localStorage.getItem(key) || '{}')
        } catch (error) { }
        if (!data) return storage//获取storage
        //设置storage
        if (typeof data != 'object') data = {}
        for (const i in data) {
            storage[i] = data[i]
        }
        localStorage.setItem(key, JSON.stringify(storage))
        return storage//设置storage同样也可返回设置后的对象
    },
    /**
     * @description: 随机数
     * @param {*} length 数量默认32个
     * @return {*}
     */
    random: function (length) {
        if (!length) length = 32
        const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
        let randomString = '';
        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            randomString += characters.charAt(randomIndex);
        }
        return randomString;
    },
    /**
     * @description:时间 
     * @param {*} format 时间参数:Y-m-d H:i:s
     * @param {*} defaultDate 需要转换的时间 如果没有则使用当前时间
     * @return {*}
     */
    date: function (format, defaultDate) {
        if (!format) format = 'Y-m-d H:i:s';
        const currentDate = !defaultDate ? new Date() : new Date(defaultDate);
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1，并确保两位数
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');
        // 替换格式字符串中的占位符
        const formattedDateTime = format
            .replace('Y', year)
            .replace('m', month)
            .replace('d', day)
            .replace('H', hours)
            .replace('i', minutes)
            .replace('s', seconds);
        return formattedDateTime;
    },
    /**
     * @description: 深拷贝数据
     * @param {*} obj
     * @return {*}
     */
    copy: function (obj) {
        if (obj === null || typeof obj !== 'object') {
            return obj;
        }
        if (Array.isArray(obj)) {
            const newArray = [];
            for (const i in obj) {
                newArray.push(this.copy(obj[i]));
            }
            return newArray;
        }
        if (typeof obj === 'object') {
            const newObj = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = this.copy(obj[key]);
                }
            }
            return newObj;
        }
    },
    /**
     * @description: 将关系数据转换成树形
     * @param {*} list 列表
     * @param {*} key key标签
     * @return {*}
     */
    listToTree: function (list, fid = 0, key = {}) {
        key.children = key.children || 'children';
        key.id = key.id || 'id';
        key.fid = key.fid || 'fid';
        const tree = []
        for (const i in list) {
            const item = list[i]
            if (item[key.fid] && item[key.id] && item[key.fid].toString() == fid.toString()) {
                item[key.children] = this.listToTree(list, item[key.id], key)
                tree.push(item);
            }
        }
        return tree
    },
    /**
     * @description: 将树形结构转换成列表
     * @param {*} tree 树形数据
     * @param {*} key key标签
     * @return {*}
     */
    treeToList: function (tree, key = {}) {
        key.children = key.children || 'children';
        key.father = key.father || 'father';
        key.treePath = key.treePath || 'treePath';
        const list = []
        for (const i in tree) {
            const item = this.copy(tree[i])
            //没有这些字段则加上
            if (!item[key.father] || !Array.isArray(item[key.father])) item[key.father] = []
            if (!item[key.children] || !Array.isArray(item[key.children])) item[key.children] = []
            if (!item[key.treePath] || !Array.isArray(item[key.treePath])) item[key.treePath] = [i]
            //取值防止被联动的数据删除
            const children = this.copy(item[key.children])
            //对加入的数据进行处理
            for (const j in item[key.father]) {//去除子集里面的多重关系
                delete item[key.father][j][key.treePath]
                delete item[key.father][j][key.father]
                delete item[key.father][j][key.children]
            }
            for (const j in item[key.children]) {//去除父级里面的多重关系
                delete item[key.children][j][key.treePath]
                delete item[key.children][j][key.father]
                delete item[key.children][j][key.children]
            }
            list.push(item)
            //如果有子集
            if (children && children.length > 0) {
                for (const j in children) {
                    children[j][key.father] = [...item[key.father], { ...item }] //父级
                    children[j][key.treePath] = [...item[key.treePath], j] //树形路径
                }
                list.push(...this.treeToList(children, key))
            }
        }
        return list
    }
}
